package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.Equipment;
import com.home.qh.model.EquipmentType;
import com.home.qh.service.EquipmentManager;
import com.home.qh.service.EquipmentTypeManager;

@Controller
public class EquipmentController {
	private transient final Log log = LogFactory.getLog(EquipmentController.class);
	private EquipmentManager equipmentManager;
	private EquipmentTypeManager equipmentTypeManager;

	@Autowired
	private ApplicationContext context;

	@Autowired
	public void setEquipmentManager(EquipmentManager equipmentManager) {
		this.equipmentManager = equipmentManager;
	}

	@Autowired
	public void setEquipmentTypeManager(EquipmentTypeManager equipmentTypeManager) {
		this.equipmentTypeManager = equipmentTypeManager;
	}

	@RequestMapping(value = "/admin/equipmentList.*", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView listCities(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'handleRequest' method...");
		}

		Equipment equipmentSearch = new Equipment();
		String paramValue = request.getParameter("name");
		String paramEquipmentTypeValue = request.getParameter("equipmentType");
		if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim())
				&& !"null".equalsIgnoreCase(paramValue)) {
			equipmentSearch.setCode(paramValue);
			equipmentSearch.setName(paramValue);
		}

		if (paramEquipmentTypeValue != null
				&& !"".equalsIgnoreCase(paramEquipmentTypeValue.trim())
				&& !"null".equalsIgnoreCase(paramEquipmentTypeValue)) {
			Long paramEquipmentTypeId = null;
			try {
				paramEquipmentTypeId = Long.parseLong(paramEquipmentTypeValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramEquipmentTypeId != null) {
				EquipmentType equipmentTypeSearch = equipmentTypeManager.get(paramEquipmentTypeId);				
				equipmentSearch.setEquipmentType(equipmentTypeSearch);
			}else{
				equipmentSearch.setEquipmentType(null);
			}
			

		}

		ModelAndView view = new ModelAndView("admin/equipmentList");
		view.addObject("equipmentTypeList", equipmentTypeManager.getAll());
		view.addObject("equipmentSearch", equipmentSearch);

		view.addObject("equipmentList",	equipmentManager.getEquipmentByEquipment(equipmentSearch, null, false, -1, -1));
		return view;

	}

}
